"""
自定义权限类
定义了各种API访问权限
"""
from rest_framework import permissions


class IsAuthorOrAdmin(permissions.BasePermission):
    """
    只允许作者或管理员访问
    用于小说创建和修改API
    """

    def has_permission(self, request, view):
        return request.user and (request.user.role == 'author' or request.user.is_staff)


class IsNovelAuthorOrAdmin(permissions.BasePermission):
    """
    只允许小说的作者或管理员访问
    用于章节管理API
    """

    def has_object_permission(self, request, view, obj):
        # obj可能是Chapter或Novel
        if hasattr(obj, 'author'):
            # 如果是Novel对象
            return obj.author == request.user or request.user.is_staff
        elif hasattr(obj, 'novel'):
            # 如果是Chapter对象
            return obj.novel.author == request.user or request.user.is_staff
        return False


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    对象所有者可以编辑，其他用户只读
    用于用户个人资料API
    """

    def has_object_permission(self, request, view, obj):
        # 读取权限允许任何请求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 写入权限只允许对象的所有者
        return obj == request.user


class IsAdminUser(permissions.BasePermission):
    """
    只允许管理员用户访问
    用于管理员API
    """

    def has_permission(self, request, view):
        return request.user and request.user.is_staff


class IsAuthorOwner(permissions.BasePermission):
    """验证是否为作品所有者"""

    def has_object_permission(self, request, view, obj):
        return obj.author == request.user

